package com.cy.milktea.common.aspect;


import com.cy.milktea.common.annotation.SetUserAndTime;
import com.cy.milktea.pojo.System.BaseObject;
import com.cy.milktea.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 该切面用来自动注入用户名和添加或者修改的时间
 */
@Aspect  //声明切面
@Component  //声明由spring容器管理
public class SetUserAndTimeAspect {

    /**
     * 定义切入点
     */
    @Pointcut("@annotation(com.cy.milktea.common.annotation.SetUserAndTime)")
    public void pointCut() {
    }

    @Before(value = "pointCut()")
    public void doBefore(JoinPoint jp) {
        MethodSignature signature = (MethodSignature) jp.getSignature();
        String value = signature.getMethod().getAnnotation(SetUserAndTime.class).value();

        /* 获取当前用户名 */
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        String name = user.getUsername();

        for (Object obj : jp.getArgs()) {
            if (obj instanceof BaseObject) {
                BaseObject bo = (BaseObject) obj;
                if ("create".equals(value)) {
                    bo.setCreatedUser(name);
                    bo.setCreatedTime(new Date());
                    bo.setModifiedUser(null);
                    bo.setModifiedTime(null);
                } else if ("modify".equals(value)) {
                    bo.setCreatedUser(null);
                    bo.setCreatedTime(null);
                    bo.setModifiedUser(name);
                    bo.setModifiedTime(new Date());
                } else if("all".equals(value)){
                    Date date = new Date();
                    bo.setCreatedUser(name);
                    bo.setCreatedTime(date);
                    bo.setModifiedUser(name);
                    bo.setModifiedTime(date);
                }
            }
        }


    }
}
